package com.kw.config;

import com.kw.pojo.Configuration;
import com.kw.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * Created by Medivh on 2020/5/8.
 * 愿我出走半生,归来仍是少年
 * 解析mapper.xml
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration){
        this.configuration =  configuration;
    }


    public void parseMapper(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element rootElement =  document.getRootElement();
        List<Element> list  = rootElement.selectNodes("//select");
        String namespace = rootElement.attributeValue("namespace");
        for(Element element:list){
            MappedStatement mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setParamterType(paramterType);
            configuration.getMappedStatementMap().put(namespace+"."+id,mappedStatement);
        }

    }
}
